/**
 * 
 */
package sudoku.util.game;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarOutputStream;

import javax.swing.JLabel;
import javax.swing.JOptionPane;

import sudoku.util.Config;
import sudoku.util.Language;

/**
 * Klass netist jari tõmbamiseks ja selle salvestamiseks kõvakettale.
 * 
 * @author Romet
 */
public class Updater {

  /**
   * Tõmbab faili netist ja salvestab selle. Vea korral teavitab sellest.
   * 
   * @param file
   *          faili aadress, mis netist tõmmatakse
   * @param name
   *          faili nimi, mis salvestatakse
   * @param language
   *          keel, et teavitused oleks lokaliseeritud
   */
  public Updater(String file, String name, Language language) {
    try {
      JarURLConnection connection = (JarURLConnection) (new URL(file).openConnection());
      JarFile jar = connection.getJarFile();
      FileOutputStream stream = new FileOutputStream(name);
      writeJarFile(jar, stream);
      stream.close();
    }
    catch (FileNotFoundException e) {
      JOptionPane.showMessageDialog(null, new JLabel(language.getUpdater_error()));
    }
    catch (Exception e) {
      Config.log(e.getClass().toString() + ": " + e.getMessage(), e.getStackTrace());
    }
  }

  /**
   * Ühe entry salvestamine
   * 
   * @param je
   * @param jarFile
   * @param jos
   * @throws IOException
   */
  private static void writeJarEntry(JarEntry je, JarFile jarFile, JarOutputStream jos) throws IOException {
    jos.putNextEntry(je);
    byte[] buffer = new byte[2048];
    int read = 0;
    InputStream is = jarFile.getInputStream(je);
    while ((read = is.read(buffer)) > 0) {
      jos.write(buffer, 0, read);
    }
    jos.closeEntry();
    is.close();
  }

  /**
   * Tõmmatud jari salvestamine
   * 
   * @param jarFile
   * @param outputStream
   * @throws NoSuchAlgorithmException
   * @throws InvalidKeyException
   * @throws SignatureException
   * @throws IOException
   */
  private void writeJarFile(JarFile jarFile, FileOutputStream outputStream) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, IOException {
    JarOutputStream jos = new JarOutputStream(outputStream);

    Enumeration<JarEntry> allEntries = jarFile.entries();
    while (allEntries.hasMoreElements()) {
      JarEntry entry = allEntries.nextElement();
      writeJarEntry(entry, jarFile, jos);

    }
    jos.flush();
    jos.finish();
    jos.close();
    jarFile.close();
    outputStream.close();
  }
}
